import "./App.css";
import {Suspense} from "react"
import {createBrowserRouter, RouterProvider, RouteObject} from "react-router-dom"
import routes from "./routes"
import { RouteConfig } from './routes/type';
import AuthGuard from "./components/AuthGuard"
import ErrorPage from "./components/ErrorPage"
import Loading from './components/Loading';
// import NotFound from "./components/NotFound"
 
// 为路由添加权限守卫（支持嵌套路由）
const createRoutesWithGuard = (routes:RouteConfig[]):RouteObject[] => {
  return routes.map(route => ({
    ...route,
    element: (
      <AuthGuard 
        element={route.element} 
        requiresAuth={route.requiresAuth} 
        roles={route.roles} 
      />
    ),
    // 递归处理子路由
    children: route.children ? createRoutesWithGuard(route.children) : undefined
  }));
};
 
// 关键修正：创建路由时不传入 errorElement，而是在路由配置中定义
const router = createBrowserRouter([
  // 添加顶级路由包裹，定义全局错误页面
  {
    path: '/',
    errorElement: <ErrorPage />, // 全局错误页面在这里定义
    children: createRoutesWithGuard(routes) // 原路由作为子路由
  }
]);
 
const App = () => {
  return (
    <Suspense fallback={<Loading />}>
      <RouterProvider router={router} />
    </Suspense>
  );
};
 
export default App;